<template>
    <img v-if="fileSuffix === 'png' ||
        fileSuffix === 'jpg' ||
        fileSuffix === 'jpeg' ||
        fileSuffix === 'ico' ||
        fileSuffix === 'bmp' ||
        fileSuffix === 'gif'
        " slot="content" :src="imageSrc" alt="description" style="max-width: 100%" />
    <VueOfficeDocx v-else-if="fileSuffix === 'doc' || fileSuffix === 'docx'" style="height: 82vh" :src="imageSrc" />
    <VueOfficeExcel v-else-if="fileSuffix === 'xls' || fileSuffix === 'xlsx'" style="height: 82vh" :src="imageSrc" />
    <VueOfficePdf v-else-if="fileSuffix === 'pdf'" :src="imageSrc" />
    <div v-else >{{ textContent }}</div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
//引入VueOfficeDocx组件
import VueOfficeDocx from '@vue-office/docx'
//引入相关样式
import '@vue-office/docx/lib/index.css'
//引入VueOfficeExcel组件
import VueOfficeExcel from '@vue-office/excel'
//引入相关样式
import '@vue-office/excel/lib/index.css'
//引入VueOfficePdf组件
import VueOfficePdf from '@vue-office/pdf'

import axios from "axios";

const textContent = ref('');

const props = defineProps({
    imageSrc: {
        type: String,
        default: '',
        required: true
    },
    // 文件类型
    fileSuffix: {
        type: String,
        default: '',
        required: false
    },
})

const transformData = (data: any) => {
    return new Promise((resolve) => {
        let reader = new FileReader();
        reader.readAsText(data, 'UTF-8');
        reader.onload = () => {
            resolve(reader.result)
        }
    })
}

const render = () => {
    // 如果是文本类型，自定义获取方式
    if (props.fileSuffix !=='jpg'&&props.fileSuffix !=='png'
    &&props.fileSuffix !=='jpeg'&&props.fileSuffix !=='ico'&&props.fileSuffix !=='bmp'
    &&props.fileSuffix !=='gif'&&props.fileSuffix !=='doc'&&props.fileSuffix !=='docx'
    &&props.fileSuffix !=='xls'&&props.fileSuffix !=='xlsx') {
        axios.get(props.imageSrc, {
            responseType: "blob",
            transformResponse: [
                async function (data) {
                    return await transformData(data);
                },
            ],
        }).then(res => {
            res.data.then((data: any) => {
                textContent.value = data;
            })
        })
    }
}
// defineExpose({
//     render
// });
render()
/* // 渲染失败
const errorHandler = () => {
    ElMessage.warning('渲染失败，请尝试重新打开！')
} */

</script>